<?php

namespace App\Http\Controllers;

use App\Baike;
use Illuminate\Http\Request;

class BaikeController extends Controller
{
	/**
	 * Display a listing of the resource.
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function index(Request $request)
	{
		//

		$page = $request->input('page', 1);
		$catid = $request->input('catid', 1);
		$pageSize = 5;
		$offset = ($page - 1) * $pageSize;
		$data['data'] = Baike::where(['catid' => $catid])->offset($offset)->limit($pageSize)->get();
		$data['total_page'] = Baike::where([])->count();
		if($data) {
			return [
				'code'    => 200,
				'message' => 'ok',
				'data'    => $data
			];
		} else {
			return [
				'code'    => 200,
				'message' => 'ok',
				'data'    => []
			];
		}
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function create()
	{
		//
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @param  \Illuminate\Http\Request $request
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function store(Request $request)
	{
		$validator = Validator::make($request->all(), [
			'title' => 'required|unique:baike'
		]);
		if($validator->fails()) {
			return $this->jsonRes(0, "请检查传入参数");
		}
		//验证重复
		$BaikeData = Baike::where('title', '=', $request->input('title'))->get(array('id'))->toArray();
		if(!empty($BaikeData)) {
			return $this->jsonRes(0, "不能重复");
		}

		$baikeDatas = Baike::create($request->all());
		return $this->jsonRes(1, $baikeDatas);
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  \App\Baike $baike
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function show(Baike $baike)
	{
		//
		return $this->jsonRes(1, $baike);
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  \App\Baike $baike
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function edit(Baike $baike)
	{
		//
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  \Illuminate\Http\Request $request
	 * @param  \App\Baike               $baike
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function update(Request $request, Baike $baike)
	{
		//
		$baike->update($request->all());
		return $this->jsonRes(1, $baike);
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  \App\Baike $baike
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function destroy(Baike $baike)
	{
		//
	}
}
